﻿using Library.AppWeb;
using MPR.Poker.Model.SYS;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MPR.Poker.DALEntity.SYS
{
    public class DAL_Member
    {
        public DAL_Member()
        {
        }

        #region Insert/Update/Delete

        /// <summary>
        /// Thêm Thành viên
        /// </summary>
        /// <param name="objMember"></param>
        /// <returns></returns>
        public ResultMessage Insert(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            objResultMessage = CheckExist(objMember.IDSys,objMember.Email);
            if (objResultMessage.IsError) return objResultMessage;

            objResultMessage = InsertNoCheck(objMember);

            return objResultMessage;
        }

        /// <summary>
        /// Kiểm Tra Thành viên Đã Tồn Tại
        /// </summary>
        /// <param name="strIDSys"></param>
        /// <param name="strMemberID"></param>
        /// <returns></returns>
        public ResultMessage CheckExist(Int64 intIDSys,string strEmail)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                Library.DataAccess.IData objIData = Library.DataAccess.Data.CreateData(DAL_Globals.ConnectString);
                objIData.ConnectNoEncrypt();
                
                SqlParameter[] para = new SqlParameter [2];
                para[0] = new SqlParameter("@IDSys", intIDSys);
                para[1] = new SqlParameter("@Email", strEmail);

                objIData.CreateStoredProcedue("sp_SYS_Member_Check");
                objIData.AddParameter(para);

                DataTable dt = objIData.GetDataTableProcedure();
                if (dt != null && dt.Rows.Count > 0)
                {
                    objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.No_Error, "Thành viên đã tồn tại", string.Empty);
                }

                //using (PokerLife db = new PokerLife())
                //{
                //    SYS_Member Member = db.SYS_Members.FirstOrDefault(i => i.IsDeleted == false & i.Email == objMember.Email & i.IDSys != objMember.IDSys);

                //    if (Member != null && Member.IDSys > 0)
                //    {
                //        objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.No_Error, "Thành viên đã tồn tại", string.Empty);
                //    }
                //}
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.CheckData, "Lỗi kiểm tra tồn tại Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> CheckExist");
                return objResultMessage;
            }
            return objResultMessage;
        }

        /// <summary>
        /// Thêm mới Thành viên chưa kiểm tra tồn tại
        /// </summary>
        /// <param name="objMember"></param>
        /// <returns></returns>
        public ResultMessage InsertNoCheck(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            SYS_Member Member = new SYS_Member();

            try
            {
                using (PokerLife db = new PokerLife())
                {
                    
                    Member.Email = objMember.Email;
                    Member.Password = Library.AppWeb.Cryptography.HashingMD5(objMember.Password);
                    Member.DisplayName = objMember.DisplayName;
                    Member.FirstName = objMember.FirstName;
                    Member.LastName = objMember.LastName;
                    Member.Gender = objMember.Gender;
                    Member.DateofBirth = objMember.DateofBirth;
                    Member.Country = objMember.Country;
                    Member.Province = objMember.Province;
                    Member.ImageUrl = objMember.ImageUrl;
                    Member.Phone = objMember.Phone;
                    Member.OrderIndex = db.SYS_Members.Count() + 1;
                    Member.IsActived = objMember.IsActived;

                    db.SYS_Members.Add(Member);
                    db.SaveChanges();
                }

                objMember.IDSys = Member.IDSys;
                DataCache.ClearDataCache.MemberCache();
                DAL_Event.Insert("Thêm mới Thành viên - " + objMember.Email.ToString(), 0, ResultMessage.ErrorTypes.Insert.ToString());
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.Insert, "Lỗi thêm mới Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> Insert");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Thêm mới Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Cập nhật Thành viên
        /// </summary>
        /// <param name="objMember"></param>
        /// <returns></returns>
        public ResultMessage Update(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            objResultMessage = CheckExist(objMember.IDSys, objMember.Email);
            if (objResultMessage.IsError) return objResultMessage;

            objResultMessage = UpdateNoCheck(objMember);

            return objResultMessage;
        }

        /// <summary>
        /// Cập nhật Thành viên chưa kiểm tra tồn Tại
        /// </summary>
        /// <param name="objMember"></param>
        /// <returns></returns>
        public ResultMessage UpdateNoCheck(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                using (PokerLife db = new PokerLife())
                {

                    SYS_Member Member = db.SYS_Members.FirstOrDefault(i => i.IDSys == objMember.IDSys);
                    Member.Email = objMember.Email;
                    Member.Password = Library.AppWeb.Cryptography.HashingMD5(objMember.Password);
                    Member.DisplayName = objMember.DisplayName;
                    Member.FirstName = objMember.FirstName;
                    Member.LastName = objMember.LastName;
                    Member.Gender = objMember.Gender;
                    Member.DateofBirth = objMember.DateofBirth;
                    Member.Country = objMember.Country;
                    Member.Province = objMember.Province;
                    Member.ImageUrl = objMember.ImageUrl;
                    Member.Phone = objMember.Phone;
                    Member.IsActived = objMember.IsActived;

                    db.SaveChanges();
                }
                DataCache.ClearDataCache.MemberCache();
                DAL_Event.Insert("Cập nhật Thành viên - " + objMember.Email.ToString(),0, ResultMessage.ErrorTypes.Update.ToString());
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.Update, "Lỗi cập nhật Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> Update");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Cập nhật Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Xóa Thành viên
        /// </summary>
        /// <param name="strIDSys"></param>
        /// <returns></returns>
        public ResultMessage Delete(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            objResultMessage = CheckRelationship(objMember);
            if (objResultMessage.IsError) return objResultMessage;

            objResultMessage = DeleteNoCheck(objMember);

            return objResultMessage;
        }

        /// <summary>
        /// Xóa đơn vị tiền tệ
        /// </summary>
        /// <param name="intMemberIDSys">Mã hệ thống đơn vị tiền tệ</param>
        /// <param name="intDeletedUser">Mã người dùng</param>
        /// <returns></returns>
        public ResultMessage Delete(int intMemberIDSys, int intDeletedUser)
        {
            ResultMessage objResultMessage = new ResultMessage();
            SYS_Member objMember = new SYS_Member();
            objMember.IDSys = intMemberIDSys;

            objResultMessage = CheckRelationship(objMember);
            if (objResultMessage.IsError) return objResultMessage;

            objResultMessage = DeleteNoCheck(objMember);

            return objResultMessage;
        }

        /// <summary>
        /// Xóa đơn vị tiền tệ
        /// </summary>
        /// <param name="lstMemberIDSys">Danh sách mã hệ thông đơn vị tiền tệ</param>
        /// <param name="intDeletedUser"></param>
        /// <returns></returns>
        public ResultMessage Delete(List<int> lstMemberIDSys, int intDeletedUser)
        {
            ResultMessage objResultMessage = new ResultMessage();
            foreach (int intIDSys in lstMemberIDSys)
            {
                SYS_Member objMember = new SYS_Member();
                objMember.IDSys = intIDSys;

                objResultMessage = CheckRelationship(objMember);
                if (objResultMessage.IsError) return objResultMessage;

                objResultMessage = DeleteNoCheck(objMember);
                if (objResultMessage.IsError) return objResultMessage;
            }
            return objResultMessage;
        }

        /// <summary>
        /// Kiểm tra dữ liệu liên quan
        /// </summary>
        /// <param name="strIDSys"></param>
        /// <returns></returns>
        public ResultMessage CheckRelationship(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
               

            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.CheckData, "Lỗi kiểm tra dữ liệu liên quan Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> CheckRelationship");
                return objResultMessage;
            }
            return objResultMessage;
        }

        /// <summary>
        /// Xóa Thành viên chưa kiểm tra dữ liệu liên quan
        /// </summary>
        /// <param name="strIDSys"></param>
        /// <returns></returns>
        public ResultMessage DeleteNoCheck(SYS_Member objMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                using (PokerLife db = new PokerLife())
                {
                    SYS_Member Member = db.SYS_Members.FirstOrDefault(i => i.IDSys == objMember.IDSys);
                    if (Member == null || Member.IDSys == 0)
                    {
                        objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.No_Error, "Thành viên không tồn tại", string.Empty);
                        return objResultMessage;
                    }

                    Member.IsDeleted = true;
                    Member.DeletedDate = DateTime.Now;

                    db.SaveChanges();
                }
                DataCache.ClearDataCache.MemberCache();
                DAL_Event.Insert("Xóa Thành viên - " + objMember.Email.ToString(), 0, ResultMessage.ErrorTypes.Insert.ToString());

            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.Delete, "Lỗi xóa Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> DeleteNoCheck");
                return objResultMessage;
            }
            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Xóa Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Login
        /// </summary>
        /// <param name="strEmail"></param>
        /// <param name="strPassword"></param>
        /// <returns></returns>
        public ResultMessage Login(string strEmail,string strPassword)
        {   
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                Library.DataAccess.IData objIData = Library.DataAccess.Data.CreateData(DAL_Globals.ConnectString);
                objIData.ConnectNoEncrypt();
                objIData.CreateStoredProcedue("sp_SYS_Member_Login");
                objIData.AddParameter("@Email", strEmail.Trim());
                objIData.AddParameter("@Password",Library.AppWeb.Cryptography.HashingMD5(strPassword));
                DataTable dt = objIData.GetDataTableProcedure();
                if(dt!=null && dt.Rows.Count>0)
                    return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Login Success!", string.Empty);
                else
                    return new ResultMessage(true, ResultMessage.ErrorTypes.No_Error, "Login failed. Check user and password !", string.Empty);

                //DAL_Event.Insert("Login Thành viên - " + strEmail.ToString(), 0, ResultMessage.ErrorTypes.Insert.ToString());

            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.Delete, "Login Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> Login");
                return objResultMessage;
            }
        }

        /// <summary>
        /// Login thành viên trả về đối tương Session
        /// </summary>
        /// <param name="objMemberSession"></param>
        /// <param name="strEmail"></param>
        /// <param name="strPassword"></param>
        /// <returns></returns>
        public ResultMessage Login(ref SYS_MemberSession objMemberSession, string strEmail, string strPassword)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                Library.DataAccess.IData objIData = Library.DataAccess.Data.CreateData(DAL_Globals.ConnectString);
                objIData.ConnectNoEncrypt();
                objIData.CreateStoredProcedue("sp_SYS_Member_Login");
                objIData.AddParameter("@Email", strEmail.Trim());
                objIData.AddParameter("@Password", Library.AppWeb.Cryptography.HashingMD5(strPassword));
                DataTable dt = objIData.GetDataTableProcedure();
                if (dt != null && dt.Rows.Count > 0)
                {
                    objMemberSession = Library.AppWeb.ConvertData.ConvertToModel<SYS_MemberSession>(dt);
                    return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Login Success!", string.Empty);
                }
                else
                    return new ResultMessage(true, ResultMessage.ErrorTypes.No_Error, "Login failed. Check user and password !", string.Empty);

                //DAL_Event.Insert("Login Thành viên - " + strEmail.ToString(), 0, ResultMessage.ErrorTypes.Insert.ToString());

            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.Delete, "Login Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> Login");
                return objResultMessage;
            }
        }

        #endregion

        #region Load/Search/Select

        /// <summary>
        /// Lấy thông tin Thành viên
        /// </summary>
        /// <param name="objMember"></param>
        /// <param name="strIDSys"></param>
        /// <returns></returns>
        public ResultMessage LoadInfo(ref SYS_Member objMember, int strIDSys)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                using (PokerLife db = new PokerLife())
                {
                    var Member = from gu in db.SYS_Members
                                   where gu.IDSys == strIDSys
                                   select gu;
                    objMember = new SYS_Member();
                    foreach (var obj in Member)
                    {
                        if (!Convert.IsDBNull(obj.IDSys)) objMember.IDSys = obj.IDSys;
                        if (!string.IsNullOrEmpty(obj.Email)) objMember.Email = obj.Email;
                        if (!string.IsNullOrEmpty(obj.Password)) objMember.Password = obj.Password;
                        if (!string.IsNullOrEmpty(obj.DisplayName)) objMember.DisplayName = obj.DisplayName;
                        if (!string.IsNullOrEmpty(obj.FirstName)) objMember.FirstName = obj.FirstName;
                        if (!string.IsNullOrEmpty(obj.LastName)) objMember.LastName = obj.LastName;
                        if (!Convert.IsDBNull(obj.Gender)) objMember.Gender = obj.Gender;
                        if (!Convert.IsDBNull(obj.DateofBirth)) objMember.DateofBirth = obj.DateofBirth;
                        if (!Convert.IsDBNull(obj.Country)) objMember.Country = obj.Country;
                        if (!Convert.IsDBNull(obj.Province)) objMember.Province = obj.Province;
                        if (!string.IsNullOrEmpty(obj.ImageUrl)) objMember.ImageUrl = obj.ImageUrl;
                        if (!string.IsNullOrEmpty(obj.Phone)) objMember.Phone = obj.Phone;
                        if (!Convert.IsDBNull(obj.OrderIndex)) objMember.OrderIndex = obj.OrderIndex;
                        if (!Convert.IsDBNull(obj.IsActived)) objMember.IsActived = obj.IsActived;
                        if (!Convert.IsDBNull(obj.IsDeleted)) objMember.IsDeleted = obj.IsDeleted;
                        if (!Convert.IsDBNull(obj.DeletedDate)) objMember.DeletedDate = obj.DeletedDate;
                    }
                }
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.LoadInfo, "Lấy thông tin Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> LoadInfo");
                return objResultMessage;
            }
            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Lấy thông tin Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Lấy danh sách Thành viên
        /// </summary>
        /// <param name="dtMember"></param>
        /// <returns></returns>
        public ResultMessage SearchData(ref DataTable dtMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            dtMember = new DataTable();

            try
            {
                using (PokerLife db = new PokerLife())
                {
                    dtMember = ConvertData.ConvertToDataTable<SYS_Member>(db.SYS_Members.Where(i => i.IsDeleted == false).ToList());
                }
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.SearchData, "Lấy thông tin Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> LoadInfo");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Lấy danh sách Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Lấy danh sách Thành viên dạng LIST
        /// </summary>
        /// <param name="lstMember"></param>
        /// <returns></returns>
        public ResultMessage SelectToList(ref List<SYS_Member> lstMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                using (PokerLife db = new PokerLife())
                {
                    var Member = from b in db.SYS_Members
                                   where b.IsDeleted == false
                                   orderby b.OrderIndex
                                   select b;
                    lstMember = Member.ToList();
                }
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.SelectData, "Lấy thông tin Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> LoadInfo");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Lấy danh sách Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Lấy danh sách Thành viên dạng List
        /// </summary>
        /// <param name="lstUserGroup">Đối tượng Thành viên</param>
        /// <param name="intPageSize">Số lượng Record một trang</param>
        /// <param name="intPageNumber">Lấy trang số mấy</param>
        /// <returns></returns>
        public ResultMessage SelectToList(ref List<SYS_Member> lstMember, int intPageSize, int intPageNumber)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                using (PokerLife db = new PokerLife())
                {
                    var Member = from gu in db.SYS_Members
                                   where gu.IsDeleted == false
                                   orderby gu.OrderIndex
                                   select gu;

                    lstMember = Member.Skip((intPageNumber - 1) * intPageSize).Take(intPageSize).ToList();
                }
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.SelectData, "Lấy thông tin Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> SelectToList");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Lấy danh sách Thành viên thành công", string.Empty);
        }

        /// <summary>
        /// Lấy danh sách Thành viên từ Cache
        /// </summary>
        /// <param name="lstMember"></param>
        /// <returns></returns>
        public ResultMessage SelectToListCache(ref List<SYS_Member> lstMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            objResultMessage = DataCache.GetDataCache.GetMember(ref lstMember);
            return objResultMessage;
        }

        /// <summary>
        /// Lấy những thông tin Thành viên để Cache
        /// </summary>
        /// <param name="lstMember"></param>
        /// <returns></returns>
        public ResultMessage SelectToCache(ref List<SYS_Member> lstMember)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                Library.DataAccess.IData objIData = Library.DataAccess.Data.CreateData(DAL_Globals.ConnectString);
                objIData.ConnectNoEncrypt();
                objIData.CreateStoredProcedue("sp_SYS_Member_Cache");
                DataTable dt = objIData.GetDataTableProcedure();

                lstMember = Library.AppWeb.ConvertData.ConvertToList<SYS_Member>(dt);
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.SelectData, "Lấy Cache danh sách Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> SelectToListCache");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Lấy Cache danh sách Thành viên thành công", string.Empty);
        }

        public ResultMessage SelectMember(ref SYS_Member objMember,string strEmail)
        {
            ResultMessage objResultMessage = new ResultMessage();
            try
            {
                Library.DataAccess.IData objIData = Library.DataAccess.Data.CreateData(DAL_Globals.ConnectString);
                objIData.ConnectNoEncrypt();
                objIData.CreateStoredProcedue("sp_SYS_Member_SEL");
                objIData.AddParameter("@Email", strEmail);
                DataTable dt = objIData.GetDataTableProcedure();

                objMember = Library.AppWeb.ConvertData.ConvertToModel<SYS_Member>(dt);
            }
            catch (Exception objEx)
            {
                objResultMessage = new ResultMessage(true, ResultMessage.ErrorTypes.SelectData, "Lấy thông tin Thành viên", objEx);
                DAL_Error.Insert(objResultMessage, 0, "DAL_Member --> SelectMember");
                return objResultMessage;
            }

            return new ResultMessage(false, ResultMessage.ErrorTypes.No_Error, "Lấy thông tin Thành viên thành công", string.Empty);
        }

        #endregion
    }
}
